# utils/logger.py（正确版本）
import logging
import os
from datetime import datetime
from utils.config_loader import get_config

# 全局日志配置
_log_config = None

def setup_logger(name: str, log_level: str = None) -> logging.Logger:
    """设置并返回一个日志记录器"""
    global _log_config
    if _log_config is None:
        config = get_config()
        _log_config = config.get("logging", {}) if config else {}
    
    if log_level is None:
        log_level = _log_config.get("level", "INFO")
    
    logger = logging.getLogger(name)
    logger.setLevel(log_level)
    # 防止重复添加 handler
    if not logger.handlers:
        # 创建格式器
        formatter = logging.Formatter(
            '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        # 创建控制台处理器
        console_handler = logging.StreamHandler()
        console_handler.setLevel(log_level)
        console_handler.setFormatter(formatter)
        logger.addHandler(console_handler)
        # 创建文件处理器
        if _log_config.get("file_logging", True):
            log_dir = _log_config.get("log_dir", "data/logs")
            os.makedirs(log_dir, exist_ok=True)
            today = datetime.now().strftime("%Y-%m-%d")
            log_file = os.path.join(log_dir, f"{today}.log")
            file_handler = logging.FileHandler(log_file, encoding='utf-8')
            file_handler.setLevel(log_level)
            file_handler.setFormatter(formatter)
            logger.addHandler(file_handler)
    return logger

class InteractionLogger:
    """交互日志记录器"""
    def __init__(self):
        self.log_dir = "data/qa_history"
        os.makedirs(self.log_dir, exist_ok=True)
        self.logger = setup_logger("interaction")
    
    def log(self, user_id: int, question: str, answer: str):
        """记录一次问答交互"""
        try:
            today = datetime.now().strftime("%Y-%m-%d")
            log_file = os.path.join(self.log_dir, f"qa_{today}.csv")
            
            # 如果文件不存在，创建并写入标题行
            if not os.path.exists(log_file):
                with open(log_file, "w", encoding="utf-8") as f:
                    f.write("timestamp,user_id,question,answer\n")
            
            # 写入日志
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            with open(log_file, "a", encoding="utf-8") as f:
                f.write(f'"{timestamp}","{user_id}","{question}","{answer}"\n')
                
            self.logger.info(f"记录交互: {user_id} - Q: {question[:20]}...")
        except Exception as e:
            self.logger.error(f"记录交互失败: {e}")